<script setup lang="ts" name="UploadPublicHealthPlatform">
import {onActivated, ref, reactive} from 'vue'
import {ElMessage, FormRules} from 'element-plus'
import {HeaderData, Operation as Oper, RowOperbuttons} from '@/components/dTable/dTable'
import {OperButton, SearchButton, SearchFromItem, SearchFromJustify} from '@/components/dTable/dHeader'
import {PageConfig, defaultPage, defaultPageSize, defaultPageSizes, defaultLayout} from '@/components/dTable/dFooter'
import {ColorTheme, SeleteData} from '@/api/config'
import operation from '@/components/dTable/components/operation.vue'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import {Alphanumeric, checkIsJSON, downFile} from '@/util/common'
import {exportPlatform, getUploadPlatformList, UploadPlatformList, UploadPlatformParams} from '@/api/dataManagement/uploadPublicHealthPlatform'
import {getTeamListAll} from '@/api/publicHealthExamination/communitySettings'
//当前页面 表格数据 定义
const tableData = ref<Array<UploadPlatformList & RowOperbuttons>>([])

//显示加载状态
const showLoading = ref(false)

// 勾选的列表id
const selectionIdList = ref<Array<string>>([])

//表格头部数据定义
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'checkupNo',
    label: '体检ID',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'gwOrgCode',
    label: '单位编码',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'personName',
    label: '姓名',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'idNo',
    label: '身份证号',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'teamName',
    label: '社区',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'phyDate',
    label: '体检日期',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'resultStatusName',
    label: '状态',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'result',
    label: '结果',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'oper',
    label: '操作',
    columnType: 'slot',
    align: 'center',
    width: '70',
    fixed: 'right'
  }
])

// 社区下拉
const selectTeamLsit = ref<Array<SeleteData>>([])

// 是否下拉
const selectList = ref<Array<SeleteData>>([
  {label: '是', value: 1},
  {label: '否', value: 2}
])

//搜索项数据定义
const searchFromItems = ref<Array<SearchFromItem>>([
  {label: '体检日期', placeholder: ['开始时间', '结束时间'], type: 'antdRange', prop: 'phyDate', showTime: false, changeSubmit: true, dateFormat: 'YYYY-MM-DD', style: {width: '320px'}},
  {label: '身份证号', placeholder: '请输入身份证号', prop: 'idNo', type: 'input', enterSubmit: true},
  {label: '社区', placeholder: '请选择社区', prop: 'teamId', type: 'selete', seleteData: selectTeamLsit.value, changeSubmit: true, filterable: true},
  {label: '是否上传', placeholder: '请选择是否上传', prop: 'uploadStatus', type: 'selete', seleteData: selectList.value, changeSubmit: true},
  {label: '是否成功', placeholder: '请选择是否成功', prop: 'resultStatus', type: 'selete', seleteData: selectList.value, changeSubmit: true}
])

const searchFromRules = reactive<FormRules>({
  idNo: [
    {
      message: '长度应不超过18个字符',
      max: 18,
      trigger: ['change', 'blur']
    },
    {message: '请输入数字、字母', pattern: Alphanumeric, trigger: ['change', 'blur']}
  ]
})

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})

const searchFromData = reactive<UploadPlatformParams>({
  page: pageConfig.value.currentPage,
  limit: pageConfig.value.pageSize
})

//表头按钮
const operButtons = ref<Array<OperButton>>([
  {
    label: '上传',
    type: 'noraml',
    iconConfig: {icon: 'common-upload', type: 'custom'},
    code: 'upload'
  },
  {
    label: '导出',
    type: 'noraml',
    iconConfig: {icon: 'common-import', type: 'custom'},
    code: 'export'
  }
])

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([{type: 'search'}, {type: 'clear'}])

//操作按钮定义
const rowOperButtons: Array<Oper> = [
  {
    code: 'edit',
    label: '上传',
    iconConfig: {
      icon: 'common-upload',
      type: 'custom',
      color: ColorTheme,
      size: 20
    }
  }
]

//后端数据拼接字段事件
const setTableData = (data: Array<UploadPlatformList>) => {
  const dataArr: Array<UploadPlatformList & RowOperbuttons> = []
  data.forEach((item) => {
    dataArr.push({...item, oper: rowOperButtons})
  })
  tableData.value = dataArr
}

//搜索数据事件
const searchData = (resetPage?: boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1
  // 请求参数
  const params: UploadPlatformParams = {
    ...searchFromData
  }
  params.page = pageConfig.value.currentPage
  params.limit = pageConfig.value.pageSize
  searchFromData.phyDate?.length ? (params.startTime = searchFromData.phyDate[0] + ' 00:00:00') : delete params.startTime
  searchFromData.phyDate?.length ? (params.endTime = searchFromData.phyDate[1] + ' 23:59:59') : delete params.endTime
  delete params.phyDate
  getUploadPlatformList(params)
    .then((res) => {
      showLoading.value = false
      const {data} = res.data
      pageConfig.value.total = data.total === null ? 0 : data.total
      setTableData(data.records)
    })
    .catch((error) => {
      showLoading.value = false
      console.warn(error)
    })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  searchData(true)
}

/**
 * @description: 勾选
 * @param {*} rows
 * @return {*}
 */
const onMultipleSelection = (rows: Array<UploadPlatformList>) => {
  selectionIdList.value = rows.map((item) => {
    return item.id
  })
}

//操作按钮事件
const onOperation = (name: string) => {
  if (name === 'upload') {
    console.log('upload')
  } else if (name === 'export') {
    if (tableData.value.length === 0) {
      ElMessage.warning('当前搜索条件下暂无数据导出！')
      return
    }
    // 请求参数
    const params: UploadPlatformParams = {
      ...searchFromData
    }
    searchFromData.phyDate?.length ? (params.startTime = searchFromData.phyDate[0] + ' 00:00:00') : delete params.startTime
    searchFromData.phyDate?.length ? (params.endTime = searchFromData.phyDate[1] + ' 23:59:59') : delete params.endTime
    delete params.phyDate
    delete params.page
    delete params.limit
    exportPlatform(params).then((res) => {
      const enc = new TextDecoder('utf-8')
      const resStr = enc.decode(new Uint8Array(res.data))
      if (checkIsJSON(resStr)) {
        const data = JSON.parse(resStr)
        if (data?.code !== 200 || !data?.success) {
          ElMessage.error(data?.msg || '未知错误')
        } else {
          data?.msg && ElMessage.warning(data?.msg)
        }
      } else {
        downFile('上传公卫平台明细.xlsx', res.data)
        ElMessage.success('上传公卫平台明细导出成功!')
      }
    })
  }
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

//操作插槽事件（编辑，删除）事件
const cellOperation = (name: string, row: UploadPlatformList) => {
  if (name === 'edit') {
    console.log(row)
  }
}

/**
 * @description: 获取社区下拉
 * @return {*}
 */
const getTeamSelect = () => {
  selectTeamLsit.value.length = 0
  getTeamListAll().then((res) => {
    res.data.data?.length &&
      res.data.data.forEach((item) => {
        selectTeamLsit.value.push({label: item.name, value: item.id || ''})
      })
  })
}

onActivated(() => {
  getTeamSelect()
  searchData()
})
</script>
<template>
  <page-container>
    <d-table-promote
      :stripe="true"
      :show-loading="showLoading"
      :oper-buttons="operButtons"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :search-form-items="searchFromItems"
      :search-from-justify="searchFromJustify"
      :search-buttons="searchButtons"
      :show-selection="true"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      @multiple-selection="onMultipleSelection"
    >
      <template #oper="scope">
        <operation :row="scope.row" :col="scope.item" @opertion-click="cellOperation" />
      </template>
    </d-table-promote>
  </page-container>
</template>
<style lang="less" scoped>
.d-operation {
  justify-content: center;
}
</style>
